class coreTiming {
    //0 未启动 1运行中 2 暂停中
    runingStatus = {
        notStart:0,
        runing:1,
        suspend:2
    };
    constructor()
    {
        this.init();
    }

    init()
    {
        this.start = null;//开始计时时间
        this.interval = null;
        this.diff = 0;
        this.diffWhenSuspend = 0;//暂停时的计时
        this.nowStatus = this.runingStatus.notStart;
    }

    
    run(callback) {
        if (this.nowStatus === this.runingStatus.runing) return;
        let _t = this;
        _t.nowStatus = this.runingStatus.runing;
        _t.start = new Date().getTime();
        this.interval = setInterval(function () {
            var now = new Date().getTime();
            _t.diff = now - _t.start + _t.diffWhenSuspend;
            callback(_t.diff)
        }, 1000);
    }

    //暂停
    suspend(callback) {
        if (this.nowStatus !== this.runingStatus.runing) return;
        this.nowStatus = this.runingStatus.suspend;

        var now = new Date().getTime();
        this.diffWhenSuspend += now - this.start;
        let diff = this.diffWhenSuspend;
        clearInterval(this.interval);
        callback(diff);
    }
    //复位
    reset(callback)
    {
        if (this.nowStatus !== this.runingStatus.suspend) return;
        this.nowStatus = false;
        clearInterval(this.interval);
        this.init();
        callback && callback();
    }

    getNowStatus()
    {
        return this.nowStatus;
    }
}

let timing = new coreTiming()


let timingBox = document.getElementById("timing");

//秒表复位
let resetTiming = document.getElementById("resetTiming");
resetTiming.addEventListener('click', () => {
    timing.reset(() => {
        timingBox.innerText = "00:00:00";
    });
})

//秒表开始、暂停计时
let startTiming = document.getElementById("startTiming");
startTiming.addEventListener('click', () => {
    if (timing.getNowStatus() === timing.runingStatus.runing) {
        timing.suspend((diff) => {
            timingBox.innerText = formatDiffTime(diff)
            startTiming.innerText = "启动"
            startTiming.style.backgroundColor = "green"
            resetTiming.style.backgroundColor = "gray"
        })
    } else {
        timing.run((diff) => {
            timingBox.innerText = formatDiffTime(diff)
            startTiming.innerText = "暂停"
            startTiming.style.backgroundColor = "grey"
            resetTiming.style.backgroundColor = "red"
        })
    }

})


function formatDiffTime(diff)
{
    let tenS = diff % 1000;
    diff = Math.floor(diff / 1000)
    let h = Math.floor(diff / 3600);
    diff %= 3600;
    let i = Math.floor(diff / 60)
    diff %= 60;
    let s = diff % 60
    return [prefixInteger(h, 2), prefixInteger(i, 2), prefixInteger(s, 2)].join(":");
}

//不足两位数前面补0
function prefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}